package cc.opcol.iot.server.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Sharable
public class ByteHandler extends ChannelInboundHandlerAdapter {
    Logger logger= LoggerFactory.getLogger(ByteHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        IoTSession ioTSession=new IoTSession();
        ioTSession.setId(ctx.channel().id().asLongText());
        ioTSession.setCtx(ctx);
        SessionManager.put(ioTSession);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //ctx.writeAndFlush(in);
        try {
            final ByteBuf in = (ByteBuf) msg;
            final String hex=ByteBufUtil.hexDump(in);
            IoTSession session=SessionManager.get(ctx.channel().id().asLongText());
            if(session!=null){
                session.onReceived(hex.toUpperCase());
            }else {
                //非法连接
                logger.debug("Illegal connection");
                ctx.close();
            }
//            final ByteBuf outBuf= Unpooled.copiedBuffer(in);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        closeChannel(ctx);
    }

    private void closeChannel(ChannelHandlerContext ctx) {
        ctx.close();
        IoTSession session=SessionManager.get(ctx.channel().id().asLongText());
        if(session!=null) {
            SessionManager.remove(session);
        }
        logger.debug(ctx + "  closed");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        closeChannel(ctx);
    }
}
